import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core'
import { FormBuilder, FormGroup, Validators } from '@angular/forms'
import { NzMessageService } from 'ng-zorro-antd'
import { RiskControlNewBaseClass } from '../baseClass'
import { PostRiskStoreService } from '../post-risk-store.service'
import { IFormItem, FormItemType, Currency } from '@shared/interfaces/common'
import { IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import { riskControlSchemeNameLength, riskControlSchemeRemarkLength } from 'app/utils/contraints'
import { PostRiskScheme, OperateType } from '@shared/interfaces/post-risk-control'
import { I18NService } from '@core'
import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { IDepositCollection } from '@shared/interfaces/deposit'
import { ActivatedRoute } from '@angular/router'
import { SettingsService } from '@delon/theme'
import { BehaviorSubject, Observable } from 'rxjs'
import { StoreDataService } from 'app/routes/store/store-data.service'
import { User } from '@shared/interfaces/user'
import {
  makeAllControlDirty,
  getAAMSAcquirer,
  getAAMSGroup,
  getAAMSMerchant,
  acquirerEditPermission,
} from 'app/utils/helpers'

@Component({
  selector: 'app-tab-base',
  templateUrl: './tab-base.component.html',
  styles: [],
})
export class TabBaseComponent extends RiskControlNewBaseClass implements NewPageAccessor, OnInit {
  formItems: IFormItem[] = []
  formItemType = FormItemType
  data: any
  type: number
  payload: IDepositCollection
  currency: string
  insCode: any
  searchChange$ = new BehaviorSubject({})
  errorTips: {}
  @ViewChild('tplCurrency') tplCurrency: TemplateRef<void>
  @ViewChild('aams') aams: TemplateRef<void>
  chosenAcquirer: IAamsItem = {}
  chosenGroup: IAamsItem = {}
  chosenMerchant: IAamsItem = {}
  userType: Boolean
  operateType = OperateType

  constructor(
    public riskStore: PostRiskStoreService,
    public fb: FormBuilder,
    private msg: NzMessageService,
    private i18n: I18NService,
    public route: ActivatedRoute,
    public storeService: StoreDataService,
    public settings: SettingsService,
  ) {
    super(fb, riskStore)
  }

  ngOnInit() {
    this.validateForm = this.initValidateForm()
    if (this.chosenAcquirer.code) {
      this.validateForm.get('insCode').setValue(this.chosenAcquirer)
    }
    this.initErrorTips()
    this.route.queryParams.subscribe(params => {
      this.type = Number(params.type)
      if (this.type === 1 || this.type === 2) {
        // 复制方案
        const tmp = this.riskStore.value
      }
    })
  }

  initFormItems(): IFormItem[] {
    return [
      {
        label: this.trans('RISK_CTRL.SCHEME_NAME'),
        formControlName: 'schemeName',
      },
      {
        label: this.trans('RISK_CTRL.SCHEME_DESC'),
        formControlName: 'schemeDesc',
      },
    ]
  }

  initErrorTips() {
    this.errorTips = {
      currency: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.CURRENCY') }),
      },
      schemeName: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_NAME') }),
        maxlength: this.trans('VALIDATION.FIXED_LENGTH', { length: riskControlSchemeRemarkLength }),
      },
      schemeDesc: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('RISK_CTRL.SCHEME_DESC') }),
        maxlength: this.trans('VALIDATION.FIXED_LENGTH', { length: riskControlSchemeRemarkLength }),
      },
    }
  }

  initValidateForm(): FormGroup {
    const { common } = this.storeService.value.store
    const authUser = this.settings.user as User
    this.userType = acquirerEditPermission(authUser)
    if (common.insCode && common.intMerCode) {
      this.chosenAcquirer = {
        num: common.insCode,
        code: common.insCode,
        name: common.insName,
        nameEN: common.insNameEN,
      }
      if (common.agentCode) {
        this.chosenGroup = {
          num: common.agentCode,
          code: common.agentCode,
          name: common.agentName,
          nameEN: common.agentNameEN,
        }
      }
      this.chosenMerchant = {
        num: common.merNum,
        code: common.intMerCode,
        name: common.merName,
        nameEN: common.merNameEN,
      }
    } else {
      this.chosenAcquirer = getAAMSAcquirer(authUser)
      this.chosenGroup = getAAMSGroup(authUser)
      this.chosenMerchant = getAAMSMerchant(authUser)
    }
    const { schemeDesc, schemeName, currency, insCode } = this.riskStore.value
    return this.fb.group({
      schemeName: [schemeName, [Validators.required, Validators.maxLength(riskControlSchemeNameLength)]],
      schemeDesc: [schemeDesc, [Validators.required, Validators.maxLength(riskControlSchemeRemarkLength)]],
      currency: [currency, [Validators.required]],
      insCode: [insCode, [Validators.required]],
    })
  }

  checkValid(): boolean {
    const valid = this.validateForm.valid
    if (valid) {
      this.pushDataToStore()
      this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    } else {
      makeAllControlDirty(this.validateForm)
      this.msg.error(this.trans('GENERAL.NOTIFICATION.VALIDATION_FAIL'))
    }
    return valid
  }

  pushDataToStore(): void {
    const tmp = this.riskStore.value
    const riskControl: PostRiskScheme = this.validateForm.value
    Object.assign(tmp, riskControl)
    this.riskStore.setValue(tmp)
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }

  currencyRequiredHandler(): void {
    this.msg.error(this.trans('VALIDATION.REQUIRED', { name: this.trans('GENERAL.INFO.TRANSACTION_CURRENCY') }))
  }
}
